import { computed, readonly, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useThrottleFn } from '@vueuse/core'
import { defineStore } from 'pinia'
import { NAVS } from '@/constant'
import { TAB_NAMES as HOME_TAB_NAMES, TAB_TYPE as HOME_TAB_TYPE, TAB_TYPE } from '@/constant/home'
import { TAB_NAMES as SEARCH_TAB_NAMES, TAB_TYPE as SEARCH_TAB_TYPE } from '@/constant/search'

export const useNavStore = defineStore('nav', () => {
  const nav = ref(NAVS.HOME)
  const refreshNav = ref(null)
  const hidden = ref(false)
  const transitionName = ref('none')
  const route = useRoute()
  const router = useRouter()

  const homeRoutes = ['home', 'lang-home']
  const homeTab = ref(null)

  const atForyouTab = computed(() => homeRoutes.includes(route.name) && route.params.tab === HOME_TAB_NAMES[HOME_TAB_TYPE.FORYOU]) // prettier-ignore

  const atFollowTab = computed(() => homeRoutes.includes(route.name) && route.params.tab === HOME_TAB_NAMES[HOME_TAB_TYPE.FOLLOW]) // prettier-ignore

  watch(homeTab, () => {
    const homeTabs = [TAB_TYPE.FOLLOW, TAB_TYPE.FORYOU]

    // 只有追蹤跟推薦會在 home 內部跳轉，其他都是外部跳轉要特別處理
    if (homeTabs.includes(homeTab.value)) toHome({ noRefresh: true })
    else {
      switch (homeTab.value) {
        case TAB_TYPE.POPULAR_CATEGORY:
          searchTab.value = SEARCH_TAB_TYPE.CATEGORY
          toSearch({ noRefresh: true })
          break
        case TAB_TYPE.POPULAR_CREATOR:
          router.push({ path: '/creators' })
          break
      }
    }
  })

  function initHomeTab(tabName) {
    for (const key in HOME_TAB_NAMES) {
      if (HOME_TAB_NAMES[key] === tabName) {
        homeTab.value = Number(key)
        break
      }
    }
    if (!homeTab.value) {
      homeTab.value = HOME_TAB_TYPE.FORYOU
    }
  }

  const searchRoutes = ['search', 'lang-search']
  const searchTab = ref(SEARCH_TAB_TYPE.SEARCH)

  const atSearchTab = computed(() => searchRoutes.includes(route.name) && route.params.tab === SEARCH_TAB_NAMES[SEARCH_TAB_TYPE.SEARCH]) // prettier-ignore

  const atCategoryTab = computed(() => searchRoutes.includes(route.name) && route.params.tab === SEARCH_TAB_NAMES[SEARCH_TAB_TYPE.CATEGORY]) // prettier-ignore

  const atFavoriteTab = computed(() => searchRoutes.includes(route.name) && route.params.tab === SEARCH_TAB_NAMES[SEARCH_TAB_TYPE.FAVORITE]) // prettier-ignore

  watch([atSearchTab, atCategoryTab, atFavoriteTab], ([s, c, f]) => {
    if (s) searchTab.value = SEARCH_TAB_TYPE.SEARCH
    if (c) searchTab.value = SEARCH_TAB_TYPE.CATEGORY
    if (f) searchTab.value = SEARCH_TAB_TYPE.FAVORITE
  })
  watch(searchTab, () => toSearch({ noRefresh: true }))

  const atHome = computed(() => nav.value === NAVS.HOME)
  const atSearch = computed(() => nav.value === NAVS.SEARCH)
  const atPublish = computed(() => nav.value === NAVS.PUBLISH)
  const atMessage = computed(() => nav.value === NAVS.MESSAGE)
  const atMine = computed(() => nav.value === NAVS.MINE)

  const refresh = useThrottleFn((toNav) => {
    console.log('refresh', toNav)
    refreshNav.value = toNav
    setTimeout(() => (refreshNav.value = null), 0)
  }, 1000)

  function refreshNavs(navs, currIndex = 0) {
    if (currIndex < navs.length) {
      refreshNav.value = navs[currIndex]
      setTimeout(() => {
        refreshNav.value = null
        setTimeout(() => refreshNavs(navs, currIndex + 1), 0)
      }, 0)
    }
  }

  function to(toNav, route, noRefresh) {
    if (nav.value !== toNav) {
      router.push(route)
    } else {
      // 主頁和搜尋頁可能只換 route 沒換 nav
      if ([NAVS.HOME, NAVS.SEARCH].includes(nav.value)) {
        router.push(route)
      }

      // 點擊相同的 nav 要通知該頁可能需要刷新
      if (!noRefresh) {
        // 在搜尋區塊點擊相同的 tab 時，若是類別或收藏不要重整頁面，直接導回搜尋頁
        if ([SEARCH_TAB_TYPE.CATEGORY, SEARCH_TAB_TYPE.FAVORITE].includes(searchTab.value)) {
          searchTab.value = SEARCH_TAB_TYPE.SEARCH
        } else {
          refresh(toNav)
        }
      }
    }
  }

  function toHome({ noRefresh = false } = {}) {
    // 從 home/Head 按下熱門分類跟熱門創作者離開後，回來時要把 tab 設回 foryou，不然右邊的頁面會錯亂
    homeTab.value = [HOME_TAB_TYPE.POPULAR_CATEGORY, HOME_TAB_TYPE.POPULAR_CREATOR].includes(homeTab.value)
      ? HOME_TAB_TYPE.FORYOU
      : homeTab.value

    to(NAVS.HOME, { name: 'home', params: { tab: HOME_TAB_NAMES[homeTab.value || HOME_TAB_TYPE.FORYOU] } }, noRefresh)
  }

  function toSearch({ noRefresh = false } = {}) {
    to(NAVS.SEARCH, { name: 'search', params: { tab: SEARCH_TAB_NAMES[searchTab.value] } }, noRefresh)
  }

  function toPublish({ noRefresh = false } = {}) {
    to(NAVS.PUBLISH, '/publish', noRefresh)
  }

  function toMessage({ noRefresh = false } = {}) {
    to(NAVS.MESSAGE, '/message', noRefresh)
  }

  function toMine({ noRefresh = false } = {}) {
    to(NAVS.MINE, '/mine', noRefresh)
  }

  function changeNav(toNav, fromNav, forceTransitionName) {
    if (forceTransitionName) {
      transitionName.value = forceTransitionName
    } else {
      setTransitionName(toNav, fromNav)
    }

    if (nav.value !== toNav) {
      nav.value = toNav
    }
  }

  function hide() {
    hidden.value = true
  }

  function show() {
    hidden.value = false
  }

  function setTransitionName(toNav, fromNav) {
    if (toNav === fromNav) {
      transitionName.value = 'none'
      return
    }

    if (toNav === -1) {
      transitionName.value = 'zoom-in'
      return
    }

    if (fromNav === -1) {
      transitionName.value = 'zoom-out'
      return
    }

    if (toNav < fromNav) {
      transitionName.value = 'slide-right'
      return
    }

    if (toNav > fromNav) {
      transitionName.value = 'slide-left'
    }
  }

  return {
    nav: readonly(nav),
    refreshNav: readonly(refreshNav),
    hidden: readonly(hidden),
    transitionName: readonly(transitionName),
    homeTab,
    searchTab,
    atHome,
    atForyouTab,
    atFollowTab,
    atSearch,
    atSearchTab,
    atCategoryTab,
    atFavoriteTab,
    atPublish,
    atMessage,
    atMine,
    initHomeTab,
    refreshNavs,
    changeNav,
    toHome,
    toSearch,
    toPublish,
    toMessage,
    toMine,
    hide,
    show,
  }
})
